package com.bs.demo.config;

import com.bs.common.utils.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author bingshao
 * @date 2022/12/7
 **/
@Log4j2
@RestControllerAdvice
public class LogResponseBodyAdvice implements ResponseBodyAdvice<Result> {

    /**
     * 判断支持的类型
     *
     * @param returnType
     * @param converterType
     * @return
     * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter,
     * java.lang.Class)
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getMethod().getReturnType().isAssignableFrom(Result.class);
    }

    /**
     * 操作
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object,
     * org.springframework.core.MethodParameter,
     * org.springframework.http.MediaType, java.lang.Class,
     * org.springframework.http.server.ServerHttpRequest,
     * org.springframework.http.server.ServerHttpResponse)
     */
    @Override
    public Result beforeBodyWrite(Result body, MethodParameter returnType, org.springframework.http.MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        log.info("body======={}", body);
        // 此处可以将结果集加密
//        body.setData(Md5Crypt.md5Crypt(body.getData().toString().getBytes(StandardCharsets.UTF_8)));
//        body.setCode(500);
        return body;
    }


}
